package com.gomoku.botrunning.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;

public class Bot2 implements java.util.function.Supplier<JSONObject> {
    private static final int BOARD_SIZE = 16;

    private int[][] parseTo2DArray(JSONArray jsonArray) {
        int[][] map = new int[BOARD_SIZE][BOARD_SIZE];
        for (int i = 1; i < BOARD_SIZE; i++) {
            JSONArray innerArray = jsonArray.getJSONArray(i);
            for (int j = 1; j < BOARD_SIZE; j++) {
                map[i][j] = innerArray.getIntValue(j);
            }
        }
        return map;
    }
    public JSONObject nextMove(String input) {
        //input 传入的是一个二维数组标记这黑白棋子的位置
        JSONArray jsonArray = JSON.parseArray(input);
        int[][] map = parseTo2DArray(jsonArray);
        //默认 1表示黑棋，2表示白棋 最后返回
        Random random = new Random();

        // 生成1-15之间的随机数（包括1和15）
        int row = random.nextInt(15) + 1;
        int col = random.nextInt(15) + 1;
        while (true) {
            if (map[row][col] != 0) {
                row = random.nextInt(15) + 1;
                col = random.nextInt(15) + 1;
            } else
                break;
        }
        //System.out.println("botmove:row " + row + " col" + col);
        JSONObject res = new JSONObject();
        res.put("r", row);
        res.put("c", col);
        return res;
    }

    @Override
    public JSONObject get() {
        File file = new File("input.txt");
        try (Scanner sc = new Scanner(file)) {
            // 优化部分：读取全部内容（原 sc.next() 仅读第一个空格前的字符，若JSON带空格会解析失败）
            StringBuilder inputBuilder = new StringBuilder();
            while (sc.hasNextLine()) {
                inputBuilder.append(sc.nextLine().trim());
            }
            String input = inputBuilder.toString();
            return nextMove(input);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("未找到 input.txt 文件，无法读取棋盘信息", e);
        }
    }
}